const packageInfo = require('./package.json');
const path = require('path');
const webpack = require('webpack');
const globals = require('./global-vars.json');
const px2rem = require('postcss-plugin-px2rem');
const TerserPlugin = require('terser-webpack-plugin');
const { mergeSiteToEnv } = require('./build/sites');
const env = mergeSiteToEnv(process.env.npm_config_site, process.env);

const assetDir = `static/${packageInfo.name}`;

const [globalConstants, globalModules] = Object.entries(globals).reduce((cate, entry) => {
    if (typeof entry[1] === 'string') {
        cate[0].push(entry);
    } else {
        cate[1].push(entry);
    }
    return cate;
}, [[], []]);

function pathResolve(dir) {
    return path.resolve(__dirname, dir);
}

// 静态资源前缀，设置cdn等
function getPublicPath() {
    return `${env.VUE_APP_CDN || ''}/`;
}


function loaders(module) {
    // // nest & async
    // module.rule('router').test(/router\/\.idx$/)
    //   .use('toml-router-loader')
    //   .loader('toml-router-loader')
    //   .options({
    //     '404': '@/views/error/404.vue'
    //   }).end();

    module.rule('toml').test(/\.toml$/)
        .use('toml-loader')
        .loader('toml-loader').end();

    module.rule('collector').test(/\.idx$/)
        .use('idx-loader')
        .loader('idx-loader')
        .options({
            transpilers: {
                'router': 'RouterTranspiler',
                'portal': 'PortalTranspiler',
            },
            // Global prefix config
            prefix: '/idx',
            '404': '@/views/error/404.vue',
        }).end();

}

module.exports = {
    // chainWebpack,
    lintOnSave: false,
    chainWebpack: (config) => {
        // config.resolve.alias
        //     .set("@", pathResolve("src"))
        config.resolve.alias.set('@', pathResolve('src'));

        config.plugin('html').tap((args) => {
            args[0].title = '慕课';
            args[0].baseUrl = getPublicPath();
            args[0].static = assetDir;
            return args;
        });
        config.plugin('define').tap((args) => {
            Object.assign(args[0], globalConstants);
            return args;
        });


        if (process.env.NODE_ENV === 'production') {
            config.performance
                // .hints(false)
                .maxEntrypointSize(50000000)
                .maxAssetSize(30000000)
                .assetFilter((assetFilename) => {
                    return assetFilename.endsWith('.js');
                });

            config.plugin('extract-css').tap(() => [
                {
                    filename: `${assetDir}/css/[name].[fullhash:8].css`,
                    chunkFilename: `${assetDir}/css/[name].[contenthash:8].chunk.css`,
                    ignoreOrder: true
                }
            ]);
        }

        config.output
            .filename(`${assetDir}/js/[name].[fullhash:8].js`)
            .chunkFilename(`${assetDir}/js/[name].[contenthash:8].chunk.js`);

        loaders(config.module);
    },
    configureWebpack: {
        plugins: [
            new webpack.ProvidePlugin(Object.fromEntries(globalModules))
        ],
        module: {
            rules: [
                {
                    test: /\.(png|jpe?g|gif|webp|ico)(\?.*)?$/,
                    type: 'asset/resource',
                    generator: {
                        filename: `${assetDir}/img/[name].[hash:8][ext][query]`,
                        publicPath: getPublicPath()
                    }
                },
                {
                    test: /\.(ttf|eot|woff2?)(\?.*)?$/,
                    type: 'asset/resource',
                    generator: {
                        filename: `${assetDir}/fonts/[name].[hash:8][ext][query]`,
                        publicPath: getPublicPath()
                    }
                },
                {
                    test: /\.(svg?)$/,
                    type: 'asset/source',
                    parser: {
                        dataUrlCondition: {
                            maxSize: 10 * 1024
                        }
                    },
                    generator: {
                        filename: `${assetDir}/img/[name].[hash:8][ext][query]`,
                        publicPath: getPublicPath()
                    }
                }
            ]
        },
        optimization: {
            minimize: process.env.NODE_ENV === 'production',
            minimizer: [
                new TerserPlugin({
                    // parallel: true, //使用多进程并发运行以提高构建速度 Boolean|Number 默认值： true  
                    terserOptions: {
                        compress: {
                            drop_console: true
                        },
                        // toplevel: true,
                        keep_classnames: true,
                        keep_fnames: true
                    },
                })
            ]
        }
    },
    devServer: {
        allowedHosts: 'all',
        client: {
            progress: false
        }
    },
    publicPath: getPublicPath(),
    outputDir: 'output',
    productionSourceMap: false,
    transpileDependencies: [
        /@shadom\/.+/,
        '@yanxiu/lib',
        'ch4o',
        'c2h6o',
        'globby',
    ]
};